<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of indexAction
 *
 * @author xlp
 */
class indexAction extends commonAction {

    function __construct() {
        parent::__construct();
        //获取游戏数据
        parent::_initHeader();
        $this->assign('trades' , array('ji' => '寄', 'ling' => '零', 'bao' => '保', 'shang' => '商'));
        $this->assign('colors' , array('uu898'=>'uu' , 'dd373'=>'dd','17uoo'=>'uoo','ee979'=>'ee'));
    }

    /*
     * 首页
     */
    function index() {
    	$this->display();
    }

    /*
     * 比价检索
     */
    function search() {
    	$gm = $this->_get('gm');
    	$ar = $this->_get('ar');
    	$ty = $this->_get('ty');
    	$cr = $this->_get('cr');
    	if(!$gm || !$ar || !$ty) {
    		jumpTo(U('index'));
    	}
    	$game = M('game')->where(array('abridge' => $gm))->find();
    	if(!$game || $game['status'] == 2) {
    		jumpTo(U('index'));
    	}
    	//获取头部信息
    	$this->_getTopData($game);
      //获取游戏下属广告信息
      $this->_getAdvsByGameId($game['id']); 
    	//物品类型
    	$stdmodes = M('stdmode')->where(array('game_id'=>$game['id'],'is_show'=>1))->order("`sort`")->findAll();
    	//跨区信息
    	$crossInfo = C('cross');
    	$serverInfo = M('game_server')->where(array('abridge' => $ar))->find();
    	$servers = array();
    	//存在跨区
    	if($serverInfo['cross_no']) {
    		$servers = M('game_server')->where(array('cross_no' => $serverInfo['cross_no']))->findAll();
    	}
    	//获取单位
    	$unit = M('stdmode')->field("`unit`")->where(array('abridge'=>$ty))->find();
    	$this->assign(array('gm'=>$gm,'ar'=>$ar,'ty'=>$ty,'cr'=>$cr,'stdmodes'=>$stdmodes,'cross'=>$crossInfo[$game['abridge']],'servers'=>$servers,'cross_no' => $serverInfo['cross_no'], 'unit'=>$unit['unit']));

    	//获取平台信息
    	$platforms   = D('platform')->where(array('status'=>1))->order('sort')->findAll();
		  $platCookies = myCookie('platforms') ? explode('-', myCookie('platforms')) : array();
		  //默认检索所有平台
    	if(!$platCookies) {
    		$this->setPlatCookieAll($platforms);
        $this->assign('allCheck' , 1);
    	}
      $checkCount = 0;
		  foreach ($platforms as $k => &$v) {
  			if($platCookies){
  				if(in_array($v['abridge'], $platCookies)) {
  					$v['is_check'] = true;
            $checkCount++;
  				}else{
  					$v['is_check'] = false;
  				}
  			}else{
  				$v['is_check'] = true;
  			}
		  }
      $checkPlatforms = array();
      foreach ($platforms as $vo) {
        if($vo['is_check']){
            $checkPlatforms[] = $vo['abridge'];
        }
      }
      if(count($platforms) == $checkCount) {
          $this->assign('allCheck' , 1);
      }
    	$this->assign('platforms' , $platforms);
      $this->assign('checkplatforms' , $checkPlatforms);
    	$this->display();
    }

    /*
     * 抓取爬虫信息
     */
    function getSpiderData() {
        $gm = $this->_post('gm');
        $ar = $this->_post('ar');
        $ty = $this->_post('ty');
        $cr = $this->_post('cr');
        $platform = $this->_post('platform');
        $last = $this->_postid('last' , 0);
        $resultData = array();
        T('user/parity');
        $sendPost['game'] = $gm;
        $sendPost['areaName'] = $ar;  
        $sendPost['trader'] = $cr;
        $sendPost['platforms'] = $platform;
        $resultData = parity::sendData($sendPost);
        if(isHave($resultData)) {
            if(mySession('spiderData')) {
              $spiderData = unserialize(mySession('spiderData'));
              $spiderData = array_merge($spiderData , $resultData);
              mySession('spiderData' , serialize($spiderData));
            }else{
              mySession('spiderData' , serialize($resultData));
            }
            if(isHave($last)) {
              $unit = M('stdmode')->field("`unit`")->where(array('abridge'=>$ty))->find();
              $_spider = unserialize(mySession('spiderData'));
              mySession('spiderData' , null);
              $unitPrice = array_map(create_function('$n', 'return $n["unitPrice"];'), $_spider);
              array_multisort($unitPrice, SORT_ASC, $_spider);
              if($_spider){ 
                foreach ($_spider as $key => &$val) {
                  $plat = D('platform')->where(array('abridge'=>$val['platform']))->find();
                  $val['is_charge']  = $plat['is_charge'];
                  $val['charge_url'] = $plat['url'];
                }
              }
              $this->assign('list' , $_spider);
              $this->assign('unit' , $unit['unit']);
              $this->assign('cr' , $cr);
              $this->JsonReturn('ok' , $this->getFetch('data_item') , 2);
            }else{
              $this->JsonReturn('ok', null , 1);
            }

        }else{
          $this->JsonReturn('抓取失败');
        }
        //判断ip受限次数
        // $isLimit = $this->_checkUserIP();
        // if(isHave($isLimit)) {
        //   $this->JsonReturn('error', $isLimit);
        // }else{
        //   T('user/parity');
        //   $sendPost['game'] = $gm;
        //   $sendPost['areaName'] = $ar;
        //   $sendPost['trader'] = $cr;
        //   $tempPlat = explode('-', ltrim(myCookie('platforms'),'-'));
        //   foreach ($tempPlat as $v) {
        //     $sendPost['platforms'] = $v;
        //     $temp = parity::sendData($sendPost);
        //     if(isHave($temp)) {
        //       $resultData = array_merge($resultData , $temp);
        //     }
        //   }
        //   $unitPrice = array_map(create_function('$n', 'return $n["unitPrice"];'), $resultData);
        //   array_multisort($unitPrice, SORT_ASC, $resultData);
        //   //是否需要手续费
        //   if($resultData){ 
        //     foreach ($resultData as $key => &$val) {
        //       $plat = D('platform')->where(array('abridge'=>$val['platform']))->find();
        //       $val['is_charge']  = $plat['is_charge'];
        //       $val['charge_url'] = $plat['url'];
        //     }
        //   }
        //   $this->assign('list' , $resultData);
        //   $this->assign('unit' , $unit['unit']);
        //   $this->assign('cr' , $cr);
        //   $this->JsonReturn('ok' , $this->getFetch('data_item') , 1);
        // }
    }



    /*
     * 获取ip访问次数
     */
    function _checkUserIP() {
        $ip = getUserIp();
        $where['ip'] = $ip;
        $result = M('ip_log')->where($where)->find();
        if(!$result) {
            $objData['ip'] = $ip;
            $objData['count'] = 1;
            $objData['stime'] = TIME;
            $objData['etime'] = TIME + 60;
            M('ip_log')->insert($objData);
            return false;
        }else{
            if(TIME > $result['etime']) {
              M('ip_log')->where(array('id' => $result['id']))->delete();
              return false;
            }else{
                $count = $result['count'] + 1;
                M('ip_log')->where(array('id' => $result['id']))->setInc('count' , 1);
                if(user::$userInfo['uid']) {
                    $level = user::$userInfo['user_level'];
                }else{
                    $level = 1;
                }  
                $data = array();
                switch ($level) {
                  case '1':
                    if($count > 15) {
                      $data['count'] = $count;
                      $data['limit'] = 15;
                    }
                    break;
                  case '2':
                    if($count > 20) {
                      $data['count'] = $count;
                      $data['limit'] = 20;
                    }
                    break;
                  case '3':
                    if($count > 30) {
                      $data['count'] = $count;
                      $data['limit'] = 30;
                    }
                    break;  
                }
                return $data;
            }
        }
    }



    /*
     * 获取头部游戏信息
     */
    function _getTopData($objData) {
    	$areas = D('game_area')->where(array('game_id'=>$objData['id']))->order('`sort`')->findAll();
    	$ar = $this->_get('ar');
    	$serverInfo = D('game_server')->where(array('abridge'=>$ar))->find();
    	$servers = D('game_server')->where(array('area_id' => $serverInfo['area_id']))->findAll();
    	//物品类型
    	$types = D('stdmode')->where(array('game_id'=>$objData['id'],'is_show'=>1))->order("`sort`")->findAll();
    	$typeInfo = D('stdmode')->where(array('abridge'=>$this->_get('ty')))->find();
    	$this->assign(array('areas' => $areas,'servers' => $servers, 'types' => $types));
    	$this->assign(array('game_name'=>$objData['name'],'area_name'=>$serverInfo['area_name'],'server_name'=>$serverInfo['server_name'],'type_name'=> $typeInfo['name'],'area_id' => $serverInfo['area_id']));
    }

    /*
     * 获取广告信息
     */
    function _getAdvsByGameId($game_id) {
      $where['game_id']  = $game_id;
      $where['position_id'] = 0;
      $where['status']  = 1;
      $where['stime[<=]'] = TIME;
      $where['etime[>=]'] = TIME;
      $advs = D('advs')->where($where)->find();
      $advsInfo = array();
      if($advs){
        $advsInfo[0]['img_url'] = getImgUrl($advs['img_url']);
        $advsInfo[0]['link_url'] = $advs['link_url'];
        $advsInfo[0]['title'] = $advs['title'];    
      }
      $this->assign('advs' , $advsInfo);
    }


    /*
     * 根据 game_id 获取游戏大区
     */
    function getAreaByGameId() {
    	$game_id = $this->_getid('game_id' , 0);
    	if(!$game_id) {
    		$this->JsonReturn('参数丢失');
    	}
    	$where['game_id'] = $game_id;
    	$areas = D('game_area')->where($where)->order("`sort`")->findAll();
 	    $this->assign('areas' , $areas);
      $this->JsonReturn('ok', $this->getFetch('area_item'), 1);
    } 


    /*
     * 根据 area_id 获取游戏服
     */
   	function getServerByAreaId() {
   		$area_id = $this->_getid('area_id' , 0);
   		if(!$area_id) {
   			$this->JsonReturn('参数丢失');
   		}
   		$where['area_id'] = $area_id;
   		$servers = D('game_server')->where($where)->order("`sort`")->findAll();
   		$this->assign('servers' , $servers);
      $this->JsonReturn('ok', $this->getFetch('server_item'), 1);
   	}


   	/*
     * 根据 game_id 获取比价类型
     */
   	function getStdmodeByGameId() {
   		$game_id = $this->_getid('game_id' , 0);
    	if(!$game_id) {
    		$this->JsonReturn('参数丢失');
    	}
    	$where['game_id'] = $game_id;
    	$where['is_show'] = 1;
    	$stdmodes = D('stdmode')->where($where)->order("`sort`")->findAll();
    	$this->assign('stdmodes' , $stdmodes);
      $this->JsonReturn('ok', $this->getFetch('stdmode_item'), 1);
   	}

   	/*
     * 根据 game_id 设置历史搜索
     */
   	function setHistory() {
     		$game_id = $this->_getid('game_id' , 0);
  		  $historys = myCookie('history') ? unserialize(myCookie('history')) : array();
      	if(in_array($game_id, $historys)){
      		$key = array_search($game_id, $historys);
      		unset($historys[$key]);
      		array_unshift($historys, $game_id);
      	}else{
      		array_unshift($historys, $game_id);
      		if(count($historys) > 8) {  //只保留7个历史记录
      			array_pop($historys);
      		}
      		myCookie('history' , serialize($historys));
      	}
      	$historyGames = array();
      	foreach ($historys as $v) {
      		$historyGames[] = M('game')->where(array('id'=>$v))->find();
      	}
  		$this->assign('historyGames' , $historyGames);
  		$this->JsonReturn('ok' , $this->getFetch('history_item') , 1);
    }

    /*
     * 设置所有平台Cookie
     */
    protected function setPlatCookieAll($objData) {
    	if(!$objData){
    		return;
    	}
    	$platforms = array();
    	foreach ($objData as $k => $v) {
    		$platforms[] = $v['abridge'];
    	}
    	myCookie('platforms', implode('-', $platforms));
    }


    /*
     * 设置平台筛选Cookie
     */
    function setPlatCookie() {
    	$is_check = $this->_getid('is_check');
    	$abridge  = $this->_get('abridge');
    	$platCookies = explode('-', ltrim(myCookie('platforms') , '-'));
    	if($is_check) {
    		if(in_array($abridge, $platCookies)) {
    			return;
    		}else{
    			array_push($platCookies, $abridge);
    			myCookie('platforms' , implode('-', $platCookies));
    		}
    	}else{
    		$key = array_search($abridge , $platCookies);
  			unset($platCookies[$key]);	
  			if(!empty($platCookies)){
  				myCookie('platforms' , implode('-', $platCookies));
  			}else{
  				myCookie('platforms' , null);
  			}
  		}
    }


    /*
     * 设置平台筛选Cookie
     * ajax
     */
    function setPlatAllCookie() {
        $set = $this->_getid('set',0);
        if($set == 1) {
            $objData   = D('platform')->where(array('status'=>1))->order('sort')->findAll();
            $platforms = array();
            foreach ($objData as $k => $v) {
              $platforms[] = $v['abridge'];
            }
            myCookie('platforms', implode('-', $platforms));
        }else{
            myCookie('platforms' , null);
        }
    }


    /*
     * 平台跳转中间页
     */
    function jump() {
      $to = urldecode($this->_get('to'));
      if(!$to) {
          jumpTo(U('index'));
      }
      $this->assign('jump_url' , $to);
      $this->display();
    }


    /*
     * 历史详情
     */
    function records() {
        if(!$this->_checkLogin(true)) {
            jumpTo(U('index'));
        }
        $gm = $this->_get('gm');
        $ar = $this->_get('ar');
        $ty = $this->_get('ty');
        $cr = $this->_get('cr');
        if(!$gm || !$ar || !$ty) {
          jumpTo(U('index'));
        }
        $game = M('game')->where(array('abridge' => $gm))->find();
        if(!$game || $game['status'] == 2) {
          jumpTo(U('index'));
        }
        //获取头部信息
        $this->_getTopData($game);
        $this->assign(array('gm'=>$gm, 'ty'=>$ty , 'ar'=>$ar , 'cr'=>$cr,'game'=>$game));
        $this->display();
    }
}
